package com.org.controller;

import com.blockchain.API.TimeCoinAPI;
import com.google.gson.Gson;
import com.org.pojo.NormalUser;
import com.org.common.PageBean;
import com.org.common.Result;
import com.org.service.NormalUserService;
import com.org.utils.JwtUtil;
import com.org.utils.Md5Util;
import com.org.utils.ThreadLocalUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: NormalUserController
 * Package: com.org.controller
 * Description:
 *
 * @Author Origin
 * @Create 2024/2/2 0:40
 * @Version 1.0
 */
@RestController
@RequestMapping("/normalUser")
@CrossOrigin//支持跨域
public class NormalUserController {
    @Autowired
    private NormalUserService normalUserService;

    @PostMapping("/register")
    public Result register(@RequestBody NormalUser normalUser) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {

        NormalUser u = normalUserService.findByUsername(normalUser.getUsername());
        if(u == null){
            //没有占用  注册
            normalUserService.register(normalUser);
            return Result.success();
        }
        //已占用
        return Result.error("用户名已被占用");
    }

    @PostMapping("/login")
    public Result<String> login(/*@Pattern(regexp = "^\\S{3,16}$")  String username, @Pattern(regexp = "^\\S{5,16}$")  String passwor*/
                                @RequestBody Map<String, String> params){
        String username = params.get("username");
        String password = params.get("password");
        //根据用户名查询User
        NormalUser loginNormalUser = normalUserService.findByUsername(username);

        //判断是否查询到
        if(loginNormalUser == null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确
//        if(Md5Util.getMD5String(password).equals(loginNormalUser.getPassword())){
        if(password.equals(loginNormalUser.getPassword())){
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginNormalUser.getId());
            claims.put("username", loginNormalUser.getUsername());
            claims.put("communityId", loginNormalUser.getCommunityId());
            claims.put("state", loginNormalUser.getState());
            claims.put("userType", 1);
            String token = JwtUtil.genToken(claims);


            return Result.success(token);
        }
        //登录失败
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<NormalUser> userInfo(){
        //根据用户名查询用户
        Map<String, Object> map  = ThreadLocalUtil.get();
        String username = (String) map.get("username");

        NormalUser normalUser =  normalUserService.findByUsername(username);
        return Result.success(normalUser);

    }

    @PutMapping("/update")
    public Result update(@RequestBody NormalUser normalUser){

        if (normalUser.getState().equals("时间币交易中")) {
            return Result.error("用户还有相关服务的时间币正在进行交易，请稍后");
        }
        //否则，用户名成立
        normalUserService.update(normalUser);

        return Result.success();
    }

    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam Map<String, String> params){
        String avatarUrl = params.get("avatarUrl");
        normalUserService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PostMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params){

        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }

        //校验原密码是否正确

        //调用userservice根据用户拿到原密码，再和old_pwd比较
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");

        NormalUser loginUser = normalUserService.findByUsername(username);

        if(!Md5Util.getMD5String(oldPwd).equals(loginUser.getPassword())){
            return Result.error("原密码不正确");
        }

        //new_pwd与re_pwd是否一样
        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码输入不一致");
        }

        //调用service完成密码更新
        normalUserService.updatePwd(newPwd);

        return Result.success();
    }

    @PostMapping("/updateIdentity")
    public Result updateIdentity(@RequestBody Map<String, String> params){
        //校验参数
        String name = params.get("name");
        String sex = params.get("sex");
        String phone = params.get("phone");
        String identityId = params.get("identity_id");
        String identityIdImg = params.get("identity_id_img");
        normalUserService.updateIdentity(name, sex, phone, identityId, identityIdImg);
        return Result.success();
    }

    // 老人资质审核材料
    @PostMapping("/oldmantIdentity")
    public Result oldmantIdentity(@RequestBody Map<String, String> params) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        NormalUser user = normalUserService.getById(id);
        String oldmantIdentity = params.get("oldmanIdentity");
        user.setOldmanMatrial(oldmantIdentity);
        normalUserService.updateById(user);
        return Result.success();
    }

    // 志愿者资质审核材料
    @PostMapping("/volunteerIdentity")
    public Result volunteerIdentity(@RequestBody Map<String, String> params) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        NormalUser user = normalUserService.getById(id);
        String volunteerIdentity = params.get("volunteerIdentity");
        user.setVolunteerMatrial(volunteerIdentity);
        normalUserService.updateById(user);
        return Result.success();
    }

    @GetMapping("/updateState")
    public Result updateState(Integer id, String state, String level) throws Exception {
        NormalUser user = normalUserService.getById(id);
        if (user.getState().equals("时间币交易中")) {
            return Result.error("用户还有相关服务的时间币正在进行交易，请稍后");
        }
        normalUserService.updateState(id, state, level);
        return Result.success();
    }

    @GetMapping("/findByUsername")
    public Result<NormalUser> findByUsername(String username){
        NormalUser user = normalUserService.findByUsername(username);
        if (user.getState().equals("时间币交易中")) {
            return Result.error("用户还有相关服务的时间币正在进行交易，请稍后");
        }
        return Result.success(user);
    }

    @GetMapping("/list")
    public Result<PageBean<NormalUser>> list(
            Integer pageNum,    //第几页
            Integer pageSize,   //页面容量
            @RequestParam(required = false) String username,    //非必须
            @RequestParam(required = false) String communityId,    //非必须
            @RequestParam(required = false) String name,    //非必须
            @RequestParam(required = false) String identityId,    //非必须
            @RequestParam(required = false) String phone,    //非必须
            @RequestParam(required = false) String isOldman,    //非必须
            @RequestParam(required = false) String isVolunteer,    //非必须
            @RequestParam(required = false) String sex,    //非必须
            @RequestParam(required = false) String state,   //非必须
            @RequestParam(required = false) String chainKey    //非必须
    ){
        PageBean<NormalUser> pb = normalUserService.list(pageNum, pageSize,
                                                         username, communityId, name,
                                                         identityId, phone, isOldman, isVolunteer, sex, state, chainKey);
        return Result.success(pb);
    }

    @GetMapping("/delete")
    public Result delete(Integer id){
        normalUserService.delete(id);
        return Result.success();
    }

//    // 获取用户时间币数量
//    @GetMapping("/getCoinNum")
//    public Result getCoinNum(Integer id) throws Exception {
//
//        NormalUser user = normalUserService.getById(id);
//        if (user.getState().equals("时间币交易中")) {
//            return Result.error("用户还有相关服务的时间币正在进行交易，请稍后");
//        }
//        String userPK = user.getChainKey();
//        String num = TimeCoinAPI.balanceOfCoin(userPK, userPK);
//        return Result.success(num);
//    }
//
//    // 获取用户所拥有的时间币列表
//    @GetMapping("/getCoinList")
//    public Result getCoinList(Integer id) throws Exception {
//        NormalUser user = normalUserService.getById(id);
//        if (user.getState().equals("时间币交易中")) {
//            return Result.error("用户还有相关服务的时间币正在进行交易，请稍后");
//        }
//        String userPK = user.getChainKey();
//        String coinList = TimeCoinAPI.coinOfUser(userPK, userPK);
//        return Result.success(coinList);
//    }

    // 根据id查询用户
    @GetMapping("/getInfoById")
    public Result<NormalUser> getInfoById(Integer id){
        NormalUser normalUser = normalUserService.getInfoById(id);
        if (normalUser.getState().equals("实名信息处理中")) {
            return Result.error("正在初始化用户的时间比，请稍后");
        }
        if (normalUser.getState().equals("时间币交易中")) {
            return Result.error("用户还有相关服务的时间币正在进行交易，请稍后");
        }
        return Result.success(normalUser);
    }

    @GetMapping("/updateIsOldman")
    public Result updateIsOldman(Integer id) {
        NormalUser normalUser = normalUserService.getInfoById(id);
        normalUser.setIsOldman("1");
        normalUserService.updateById(normalUser);
        return Result.success();
    }

    @GetMapping("/updateIsVolunteer")
    public Result updateIsVolunteer(Integer id) {
        NormalUser normalUser = normalUserService.getInfoById(id);
        normalUser.setIsVolunteer("1");
        normalUserService.updateById(normalUser);
        return Result.success();
    }

    @PostMapping("/updateAll")
    public Result updateAll(@RequestBody NormalUser normalUser){
        System.out.println(normalUser);
        normalUserService.updateById(normalUser);
        return Result.success();
    }
}